package org.jeecg.modules.publish.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.content.entity.BasThirdInfo;
import org.jeecg.modules.content.entity.ContentInfo;
import org.jeecg.modules.publish.entity.WeixinContent;
import org.jeecg.modules.publish.entity.WeixinUploadContent;
import org.jeewx.api.core.common.util.WeixinUtil;
import org.jeewx.api.wxsendmsg.JwSendMessageAPI;
import org.jeewx.api.wxsendmsg.util.ReadImgUrls;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.jeewx.api.core.common.HttpPostUtil.*;
import static org.jeewx.api.core.common.HttpPostUtil.IMG_BMP;

@Slf4j
public class WeixinInterface {

	public static Result<?> updoadToWeixin(List<ContentInfo> newsItemList, BasThirdInfo basThirdInfo){
		try{
			// 获取accessToken
			String accessToken = AccessTokenUtil.getAccseeToken(basThirdInfo.getClientKey(), basThirdInfo.getClientSecret());
			//2.遍历所有的图文
			List<WeixinContent> baseGraphicList = new ArrayList<WeixinContent>();
			//3.1装载图文参数

			//update-begin--Author:zhangweijian  Date: 20180820 for：位置调整
//			int i = 0;
			for(ContentInfo newsItem:newsItemList){
				WeixinContent wxContent=new WeixinContent();
				wxContent.setThumb_media_id(uploadPhoto(newsItem.getMbLogoUrl(),accessToken));
				wxContent.setAuthor(newsItem.getAuthorName());
				wxContent.setTitle(newsItem.getContentTitle());
				wxContent.setContent_source_url(newsItem.getHtmlUrl());
				wxContent.setContent(updateContent(newsItem.getContent(),accessToken));
				wxContent.setDigest(newsItem.getContentIntroduce());
				//update-begin--Author:zhangweijian Date:20181016 for：传入封面图是否展示参数
				//是否显示封面图，1为显示，0为不显示
//				wxContent.setShow_cover_pic("0");
//				if(i == 0){
//					wxContent.setShow_cover_pic("1");
//				}
				baseGraphicList.add(wxContent);
//				i++;
			}

			WeixinUploadContent graphic = new WeixinUploadContent();
			graphic.setArticles(baseGraphicList);
			String ret = uploadGroupNewsTemplate(graphic,accessToken);
			JSONObject resultJson = JSONObject.fromObject(ret);

			if(resultJson.containsKey("media_id")){
				String media_id = resultJson.get("media_id").toString();
				Result<?> result = sendMessage(media_id, accessToken);
				return result;
			}else{
				return Result.ok("图文素材上传失败!失败代码：");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("审核成功！第三方微信发送失败！");
		}
	}



		//上传图文素材
		private static String uploadGroupNewsTemplate(WeixinUploadContent graphic, String accessToken) throws Exception {
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+accessToken;
//			Map<String,Object> param = com.alibaba.fastjson.JSONObject.parseObject(JSON.toJSONString(graphic));
			String result = RestUtil.sendPostDataByJson(requestUrl,JSON.toJSONString(graphic),"utf-8");
			return result;
		}



	public static Result<?>  sendMessage(String media_id,String accessToken){
		//获取accessToken
		//调用创建标签接口
		String name="{\"filter\":{\"is_to_all\":"+true+",\"tag_id\":2},\"mpnews\":{\"media_id\":\""+media_id+"\"},\"msgtype\":\"mpnews\",\"send_ignore_reprint\":0}";
		String requestUrl="https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token="+accessToken;
		log.info("根据标签进行群发:url:"+requestUrl);
		log.info("群发参数："+name);
		com.alibaba.fastjson.JSONObject jsonObj = RestUtil.post(requestUrl,com.alibaba.fastjson.JSONObject.parseObject(name.toString()));

		//接口返回信息
		//update-begin--Author:zhangweijian  Date: 20180831 for：接口返回信息
		log.info("群发返回参数："+jsonObj);
		if(jsonObj.getString("errcode").equals("0")){
			return Result.ok(jsonObj.getString("msg_id"));
		}else{
			String errcode=jsonObj.getString("errcode");
			return Result.ok("发送失败！");
		}
		//update-end--Author:zhangweijian  Date: 20180831 for：接口返回信息

	}





	//图片上传微信服务器
	private static String uploadPhoto(String imagePath,String accessToken) {
		String media_id="";
		//获取token方法替换
		//String url=request.getSession().getServletContext().getRealPath("/")+imagePath;
		//update-begin--Author:zhaofei  Date: 20191023 for：修改图文素材上传封面图到服务器
		String url = imagePath;
		JSONObject jsonObj=sendMediaByUrl("image", url, accessToken);
		//update-end--Author:zhaofei  Date: 20191023 for：修改图文素材上传封面图到服务器
		if(jsonObj!=null){
			if(jsonObj.containsKey("errcode")){
				//author:sunkai--date:2018-09-26--for:粉丝同步错误返回码信息转义
				//String errcode = jsonObj.getString("errcode");
				//String errmsg = jsonObj.getString("errmsg");
				System.out.println("图片同步微信服务器失败! ");
				//author:sunkai--date:2018-09-26--for:粉丝同步错误返回码信息转义
			}else{
				System.out.println("图片素材同步微信服务器成功");
				media_id = jsonObj.getString("media_id");
			}
		}
		return media_id;
	}



	//替换微信图文
	private static String updateContent(String content, String accessToken) {
		if (content != null) {
			//获取token方法替换
			//String baseImageUrl = ResourceUtil.getWebProjectPath();
			//update-begin--Author:zhangweijian  Date: 20180831 for：接口方法替换
			HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			String baseImageUrl=request.getSession().getServletContext().getRealPath("/");
			//update-end--Author:zhangweijian  Date: 20180831 for：接口方法替换
			String[] urls = ReadImgUrls.getImgs(content);
			if(urls!=null){
				for(String url:urls){
					if(url == null){
						continue;
					}
					if(url.indexOf("mmbiz.qpic.cn")!=-1){
						continue;
					}
					JSONObject retObj=JwSendMessageAPI.uploadImgReturnObj(accessToken, url);
					if(null!=retObj&&retObj.containsKey("url")){
						String newUrl=retObj.getString("url");
						content = content.replace(url, newUrl);
						System.out.println("正文图片"+url+"同步微信成功!\r\n");
					}else{
						System.out.println("正文图片"+url+"同步微信成功!\r\n");
					}
				}
			}
		}

		return content;
	}


	public static JSONObject sendMediaByUrl(String fileType,String url,String token) {
		String result = null;
		JSONObject jsonobject = new JSONObject();
		jsonobject = null;
		HttpURLConnection con =null;
		OutputStream out =null;
		try{
			String requestUrl="https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ token + "&type="+fileType;
			log.info("------------------requestUr------------"+requestUrl);
			URL urlObj = new URL(requestUrl);
			con = (HttpURLConnection) urlObj.openConnection();
			con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			//--update-begin---author：zhoujf-------date:20170112--------for:设置网络超时时间-------------------------
			//设置网络超时
			con.setConnectTimeout(12000);
			con.setReadTimeout(12000);
			//--update-begin---author：zhoujf-------date:20170112--------for:设置网络超时时间-------------------------
			con.setRequestProperty("Connection", "Keep-Alive");// 设置请求头信息
			con.setRequestProperty("Charset", "UTF-8");
			String BOUNDARY = "----------" + System.currentTimeMillis();// 设置边界
			con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
			// 请求正文信息
			// 第一部分：
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // 必须多两道线
			sb.append(BOUNDARY);
			sb.append("\r\n");
			String valuename = System.currentTimeMillis()+getPicType(getURIFileBytes(url));
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ valuename + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] head = sb.toString().getBytes("utf-8");
			// 获得输出流
			out = new DataOutputStream(con.getOutputStream());
			// 输出表头
			out.write(head);
			out.write(getURIFileBytes(url));
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
			StringBuffer buffer = new StringBuffer();
			BufferedReader reader = null;
			try {
				// 定义BufferedReader输入流来读取URL的响应
				reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				if(result==null){
					result = buffer.toString();
				}
			} catch (IOException e) {
				log.info("发送POST请求出现异常！" + e);
				e.printStackTrace();
				throw new IOException("数据读取异常");
			} finally {
				if(reader!=null){
					reader.close();
				}
			}
			jsonobject = JSONObject.fromObject(result);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(out!=null){
					out.close();
				}
				if(con!=null){
					con.disconnect();
				}
			} catch (Exception e) {
			}
		}
		return jsonobject;
	}

	/**
	 * 根据文件流判断图片类型
	 * @return jpg/png/gif/bmp
	 */
	public static String getPicType(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < 4; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		String type = stringBuilder.toString().toUpperCase();
		if (type.contains("FFD8FF")) {
			return IMG_JPG;
		} else if (type.contains("89504E47")) {
			return IMG_PNG;
		} else if (type.contains("47494638")) {
			return IMG_GIF;
		} else if (type.contains("424D")) {
			return IMG_BMP;
		}else{
			return "";
		}
	}

	private static byte[] getURIFileBytes(String url) throws IOException{
		log.info("Url转字节数组前！" + url);
		//url = url.replace("http:"+File.separator,"http://").replace("\\","/");
		URL oracle = new URL(url);
		log.info("Url转字节数组之后！" + oracle);
		InputStream inStream = oracle.openStream();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

}
